﻿using System;
using System.Web.Helpers;
using AutoMapper;
using YuYuKiCms.Bl.Interface;
using YuYuKiCms.Dal.Interface;
using YuYuKiCms.Dal.Model;
using YuYuKiCms.Model;

namespace YuYuKiCms.Bl.Core
{
    internal class AccountBL : IAccountBL
    {
        private readonly IUserAccountRepository _userAccountRepository;

        public AccountBL(IUserAccountRepository userAccountRepository)
        {
            _userAccountRepository = userAccountRepository;
        }

        public bool Login(LoginVm model, string confirmationToken)
        {
            var result = false;

            // Get profile if exsist
            var account = _userAccountRepository.GetByEmail(model.Email);
            if (
                // Check if account exists
                null != account &&
                (
                    // Check if the mail was confirmed
                    (account.IsConfirmed) ||
                    // Otherwise
                    account.ConfirmationToken.Equals(confirmationToken, StringComparison.InvariantCultureIgnoreCase)
                    )
                )
            {
                var hash = HashPassword(model.Password, account.PasswordSalt);
                result = account.Password.Equals(hash);
                if (result && account.IsConfirmed == false)
                {
                    account.IsConfirmed = true;
                }
            }
            return result;
        }

        public string Registration(RegistrationVm login)
        {
            // add a user
            var account = Mapper.Map<UserAccount>(login);
            account.CreateDate = DateTime.Now;
            account.PasswordSalt = Crypto.GenerateSalt();
            account.ConfirmationToken = Guid.NewGuid().ToString().Replace("-", "");
            account.Password = HashPassword(login.Password, account.PasswordSalt);

            _userAccountRepository.InsertOrUpdate(account, account.Id);

            return account.ConfirmationToken;
        }

        private static string HashPassword(string password, string salt)
        {
            return Crypto.SHA256(string.Format("{0}{1}", Crypto.SHA256(password), salt));
        }
    }
}